import {
  getProductInfoById
} from "../../api/product.js";
import { usersBuyProduct } from "../../api/order.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    is_shoucang: 1,
    value1: 1,
    product: {},
    total_price: 0,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000
  },

  /**
   * 生命周期函数--监听页面加载
   */

  handleChange1({
    detail
  }) {
    var that = this
    this.setData({
      value1: detail.value
    })
    let num = detail.value
    let product_price = this.data.product.price
    let money = num * product_price
    that.setData({
      total_price: money.toFixed(2)
    })
  },
  onLoad: function (options) {
    console.log(options.id);

    let id = {
      id: options.id
    }
    var that = this
    getProductInfoById(id).then(res => {
      that.setData({
        product: res.data
      })
      console.log(res);
    })
  },
  buy() {
    var that = this
    let user = JSON.parse(wx.getStorageSync('usersinfo'))
    let nowDate = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0, 8)
    // console.log(this.data.product);
    // console.log(this.data.value1);
    // console.log(this.data.total_price);
    // console.log(user);
    // console.log(nowDate);

    let param = {
      no: (Math.random() * 10000000000000000).toFixed(0),
      productId: that.data.product.id,
      name: that.data.product.name,
      num: this.data.value1,
      state: 0,
      total: this.data.total_price,
      goodsImg: that.data.product.picture,
      userId: user.id,
      userName: user.realname,
      userPhone: user.phone,
      paymentTime: nowDate
    }
    usersBuyProduct(param).then( res => {
      if(res.code == '200'){
        wx.showToast({
          title: "购买成功",
          icon: 'none',
          duration: 2000
        })
        setTimeout(()=>{
          wx.reLaunch({
            url: '/pages/index/index',
          })
        },3000)
      } else {
        wx.showToast({
          title: "购买失败",
          icon: 'none',
          duration: 2000
        })
      }
      console.log(res);
    })
    console.log(param);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})